﻿using System.Collections.Generic;
using System.Linq;
using BookShop.DAL;
using BookShop.DTO;
using BookShop.Library.Common;

namespace BookShop.BLL
{
    public class ModeratorService
    {
        public static Moderator Add(Moderator moderator)
        {
            using (var repository = new ModeratorRepository())
            {
                return repository.Add(moderator);
            }
        }
        public static bool Delete(Moderator moderator)
        {
            using (var repository = new ModeratorRepository())
            {
                return repository.Delete(moderator);
            }
        }
        public static List<Moderator> GetAll()
        {
            using (var repository = new ModeratorRepository())
            {
                return repository.GetAll().ToList();
            }
        }
        public static Moderator GetById(int moderatorId)
        {
            using (var repository = new ModeratorRepository())
            {
                return repository.Find(p => p.Id == moderatorId);
            }
        }
        public static Moderator Login(string username, string password)
        {
            using (var repository = new ModeratorRepository())
            {
                password = CommonFunction.EncryptString(password);
                var mod = repository.Find(m => m.Username.Equals(username) && m.Password.Equals(password));
                return mod;
            }
        }
        public static List<Moderator> Search(int? moderatorId, string username, int page, int pageSize,
            out int count)
        {
            var repository = new ModeratorRepository();
            var returnList = new List<Moderator>();
            if (moderatorId.HasValue)
            {
                var moderator = GetById(moderatorId.Value);
                if (moderator != null)
                {
                    returnList.Add(moderator);
                }
            }
            else
            {
                returnList = repository.GetAll().ToList();
                if (!string.IsNullOrWhiteSpace(username))
                {
                    returnList = returnList.FindAll(m => m.Username.ToLower().Contains(username.Trim().ToLower()));
                }
            }
            count = returnList.Count;
            return returnList.Skip((page - 1) * pageSize).Take(pageSize).ToList();
        }
        public static Moderator Update(Moderator moderator)
        {
            using (var repository = new ModeratorRepository())
            {
                return repository.Update(moderator);
            }
        } 
    }
}
